import { DatePickerProps, Spin } from 'antd';
import dayjs from 'dayjs';
import { FC, useEffect, useLayoutEffect, useRef, useState } from 'react';

import EchartsComponent, { MyChartOption } from '@/components/EchartsComponent';
import {
  ProFormDateRangePicker,
  ProFormInstance,
  ProFormTreeSelect,
  QueryFilter,
} from '@/components/Pro';
import { getEmptyOptions } from '@/dictionary';
import { parseArray } from '@/pages/Statistics/Battery/utils';
import { statisticDodControllerGetDodList } from '@/services/ess/statisticDod';
import { formatEmptyValue } from '@/utils';
import { deviceTreeData } from '@/utils/formatterTree';
import { useIntl, useModel } from '@umijs/max';

type IProps = {
  deviceTree: deviceTreeData[];
};
const Chart: FC<IProps> = (props) => {
  const intl = useIntl();
  const { initialState } = useModel('@@initialState');
  const { deviceTree } = props;
  const formRef = useRef<ProFormInstance<API.statisticDodControllerGetDodListParams>>();
  const [loading, setLoading] = useState(false);
  const [chartOptions, setChartOptions] = useState(getEmptyOptions());
  // 统计维度
  const [deviceVal, setDeviceVal] = useState();
  // const treeData = useRef(null);
  const [treeData, setTreeData] = useState();
  useEffect(() => {
    if (deviceTree?.length) {
      setTreeData(deviceTree);
      setDeviceVal(deviceTree[0].uniqueId);
    }
  }, [deviceTree]);

  useEffect(() => {
    formRef.current.submit();
  }, [deviceVal]);
  const transformData = (options: any[]) => {
    const xAxis: string | number[] = [];
    const seriesMap = {};
    options?.forEach((item) => {
      if (!xAxis.includes(item.date)) {
        xAxis.push(item.date);
      }
      // 处理seriesData
      if (!seriesMap[item.areaName]) {
        seriesMap[item.areaName] = new Array(xAxis.length).fill(0);
      }
      const index = xAxis.indexOf(item.date);
      seriesMap[item.areaName][index] = item.dod;
    });
    const seriesData = Object.keys(seriesMap).map((key) => {
      return {
        type: 'bar',
        name: !initialState?.isArea
          ? intl.formatMessage({ id: 'statistics.analyze.depth' })
          : `${intl.formatMessage({ id: 'statistics.analyze.depth' })}_${formatEmptyValue(key)}`,
        // eslint-disable-next-line eqeqeq
        data: seriesMap[key],
        barWidth: '30%',
      };
    });
    return {
      xAxis: xAxis,
      series: seriesData,
    };
  };

  useLayoutEffect(() => {
    if (formRef.current) {
      formRef.current.submit();
    }
  }, []);

  const disabledDate: DatePickerProps['disabledDate'] = (current, { from }) => {
    const disabled = current > dayjs();

    if (from) {
      return disabled || Math.abs(current.diff(from, 'days')) >= 90;
    }

    return disabled;
  };
  const chartRef = useRef(null);
  const getFormatterOptions = (options): MyChartOption => {
    const { xAxis, series } = transformData(options);
    setLoading(false);
    return {
      dataZoom: { type: 'inside' },
      xAxis: {
        type: 'category',
        data: xAxis,
        axisTick: {
          alignWithLabel: true,
        },
        axisLabel: {
          formatter: (value: string) => {
            return dayjs(value).format('MM-DD');
          },
        },
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: true,
        },
        name: intl.formatMessage({ id: 'bigdata.unitS' }) + '%',
        nameTextStyle: {
          align: 'left',
          lineHeight: 1,
        },
      },
      tooltip: {
        show: true,
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
        // eslint-disable-next-line eqeqeq
        valueFormatter: (value) => (value == null ? '--%' : Number(value) + '%'),
      },
      grid: {
        top: 40,
        right: 10,
        left: 10,
        bottom: 0,
        containLabel: true,
      },
      series: series,
    };
  };

  return (
    <div>
      <QueryFilter<API.statisticDodControllerGetDodListParams>
        split
        params={{
          codes: deviceVal,
        }}
        formRef={formRef}
        onFinish={async (formData) => {
          if (initialState?.isArea) {
            setLoading(true);
            const params = JSON.parse(JSON.stringify(formData));
            const areaList = parseArray(deviceVal ? deviceVal : formData?.codes);
            params.areaIdList = areaList.id.join(',');
            delete params.codes;
            const res = await statisticDodControllerGetDodList(params);
            chartRef?.current.instance().clear();
            setChartOptions(getFormatterOptions(res?.data?.records));
          } else {
            setLoading(true);
            const res = await statisticDodControllerGetDodList(formData);
            chartRef?.current.instance().clear();
            setChartOptions(getFormatterOptions(res?.data?.records));
          }
        }}
        onReset={() => {
          setDeviceVal(deviceTree?.[0]?.uniqueId);
          formRef?.current?.submit();
        }}
      >
        <ProFormDateRangePicker
          name="dateRange"
          label={intl.formatMessage({ id: 'statistics.income.select' })}
          initialValue={[dayjs().subtract(6, 'day'), dayjs()]}
          fieldProps={{
            disabledDate: disabledDate,
            allowClear: false,
            autoFocus: false,
          }}
          transform={(value) => {
            if (value) {
              return {
                startDate: value[0],
                endDate: value[1],
              };
            }
          }}
        />
        {initialState?.isArea && (
          <ProFormTreeSelect
            name={'codes'}
            initialValue={deviceTree?.[0]?.uniqueId}
            label={intl.formatMessage({ id: 'statistics.work.dimensions' })}
            fieldProps={{
              value: deviceVal,
              treeData: treeData,
              fieldNames: {
                label: 'deviceName',
                value: 'uniqueId',
                children: 'subDevices',
              },
              multiple: true,
              maxTagCount: 'responsive',
              showSearch: true,
              onChange: (...args) => {
                setDeviceVal(args[0]);
              },
            }}
          ></ProFormTreeSelect>
        )}
      </QueryFilter>
      <Spin spinning={loading}>
        <EchartsComponent option={chartOptions} height={550} ref={chartRef} />
      </Spin>
    </div>
  );
};

export default Chart;
